import 'package:flutter/material.dart';
import 'package:flutter_application_cyber/pages/Message/cn_follow_list_page.dart';
import 'package:flutter_application_cyber/pages/Message/cn_message_list_page.dart';
import 'cn_bottom_input_bar.dart';
import 'cn_bottom_tool_bar.dart';
import 'package:flutter_application_cyber/tools/cn_widget_util.dart';
import 'package:flutter_application_cyber/tools/cn_media_util.dart';
import 'package:flutter_application_cyber/tools/cn_style.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';
import 'package:flutter_application_cyber/tools/cn_common_global.dart';
import 'cn_message_contentList.dart';
import 'package:flutter_application_cyber/pages/Home/cn_call_wait_page.dart';
import '../../tools/cn_event_bus.dart';
import 'package:flutter_application_cyber/net/cn_net_helper.dart';
import 'package:flutter_application_cyber/model/cn_net_response.dart';
import 'package:flutter_application_cyber/pages/Mate/Models/cn_AnchorViewModel.dart';
import '../../model/cn_strategy_model.dart';
import 'package:flutter_application_cyber/model/cn_strategy_vmodel.dart';
import 'package:flutter_application_cyber/tools/cn_app_popView.dart';
import 'package:flutter_application_cyber/pages/Mate/cn_gift_animation_view.dart';
import 'package:flutter_application_cyber/pages/Mine/cn_coinStore_Page.dart';
import 'dart:async';
import 'package:flutter_application_cyber/tools/cn_event_busUtils.dart';
import '../../tools/cn_click_utils.dart';

enum ConversationStatus {
  Normal, //正常
  VoiceRecorder, //语音输入，页面中间回弹出录音的 gif
}

class CnMessageChatPage extends StatefulWidget {
  const CnMessageChatPage({Key? key, this.arguments}) : super(key: key);
  final Map? arguments;

  @override
  State<CnMessageChatPage> createState() =>
      _MessageChatPage(arguments: this.arguments);
}

class _MessageChatPage extends State<CnMessageChatPage>
    with TickerProviderStateMixin
    implements
        BottomInputBarDelegate,
        BottomToolBarDelegate,
        MessageContentListDelegate {
  Map? arguments;
  CnBottomInputBar? bottomInputBar;
  CnBottomToolBar? bottomToolBar;
  bool multiSelect = false; //是否是多选模式
  InputBarStatus? currentInputStatus;
  List<Widget> extWidgetList = []; //加号扩展栏的 widget 列表
  List emojiList = []; // emoji 数组

  RCIMIWEngine? _engine;
  RCIMIWConversationType? conversationType;
  String? targetId;
  String? nickName;
  String? avatarUrl;
  StreamSubscription? event;

  int availableCoins = 0;
  String giftName = ""; //礼物名
  Timer? _giftTimer;
  late AnimationController _controller;
  late AnimationController _scaleController;

  RCIMIWSendMessageCallback? sendMessageCallback;
  List messageDataSource = []; //消息数组
  late MessageContentList messageContentList;
  ListView? phrasesListView;
  List phrasesList = []; // 快捷回复，短语数组
  ConversationStatus? currentStatus; //当前输入工具栏的状态
  List selectedMessageIds = []; //已经选择的所有消息Id，只有在 multiSelect 为 YES,才会有有效值
  Map burnMsgMap = Map();
  _MessageChatPage({this.arguments});
  CnStrategyModel getStrategy() {
    return CnStrategyViewModel.getInfo().strategy!;
  }
  UserInfoModel? userData = UserInfoModel();


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Text(
          nickName ?? '',
          style: TextStyle(fontSize: 18, color: Color(0xFF404040)),
          textAlign: TextAlign.center,
        ),
        centerTitle: true, //标题居中
        leading: IconButton(
            color: Colors.black,
            icon: const Icon(Icons.arrow_back_ios),
            onPressed: () => Navigator.pop(context)),
        actions: arguments?["targetId"] != getStrategy().userServiceAccountId
            ? _buildRightButtons()
            : null,
      ),
      body: GestureDetector(
        onTap: () {
          setState(() {
            // 隐藏软键盘
            FocusScope.of(context).unfocus();
          });
        },
        child: Container(
          width: double.infinity,
          color: Colors.white,
          child: Stack(children: [
            SafeArea(
                child: Column(
              children: [
                Flexible(
                  child: Stack(
                    children: <Widget>[
                      Column(children: <Widget>[
                        Flexible(child: messageContentList),
                      ]),
                      arguments?["targetId"] !=
                              getStrategy().userServiceAccountId
                          ? Positioned(
                              bottom: 30,
                              right: 10,
                              child: IconButton(
                                onPressed: () {
                                  _showGiftDialog(context,
                                      (index) {
                                    if (index == 0) {
                                      Future.delayed(Duration(seconds: 1), () {
                                        CnAppPopPageView
                                            .showCustomModalBottomSheet(
                                                context,
                                                CnCoinStorePage(
                                                  isPodPage: true,
                                                ));
                                      });
                                    } else {
                                      if (availableCoins < 39) {
                                        Future.delayed(Duration(seconds: 1),
                                            () {
                                          CnAppPopPageView
                                              .showCustomModalBottomSheet(
                                                  context,
                                                  CnCoinStorePage(
                                                    isPodPage: true,
                                                  ));
                                        });
                                      } else {
                                        setState(() {
                                          giftName =
                                              "images/icon_gift_pc${index}.png";
                                        });
                                        _startGiftTimer();
                                        _startAnimation();
                                        //扣除金币接口
                                        CnNetHelper.reviewModeConsumeData(39,
                                            (HDHResponseData configData,
                                                bool result, String msg) async {
                                          if (result) {
                                            getCoins();
                                          }
                                        });
                                      }
                                    }
                                  });
                                },
                                iconSize: 55,
                                icon: Image.asset('images/ic_gift.png'),
                              ),
                            )
                          : Container()
                    ],
                  ),
                ),
                Container(
                  // height: multiSelect ? 55 : 82,
                  child: _buildBottomInputBar(),
                ),
                _getExtentionWidget(),
              ],
            )),
            _buildExtraCenterWidget(),
            giftName == ""
                ? const SizedBox()
                : CnGiftAnimationView(giftName,
                    controller: _controller, scaleController: _scaleController),
            Container(
              padding: EdgeInsets.fromLTRB(50, 0, 50, 0),
              alignment: Alignment.center,
              child: Container(
                width: 150,
                height: 50,
                child: Text(
                  this.currentStatus == ConversationStatus.VoiceRecorder
                      ? RCString.BottomSlideUpCancel
                      : '',
                  textAlign: TextAlign.center,
                ),
              ),
            ),
          ]),
        ),
      ),
    );
  }

  _startGiftTimer() {
    if (_giftTimer != null) {
      _giftTimer?.cancel();
      _giftTimer = null;
    }
    _giftTimer ??= Timer(const Duration(seconds: 5), () {
      setState(() {
        giftName = "";
      });
    });
  }

  _startAnimation() {
    _controller.reset();
    _scaleController.reset();
    _controller.forward();
  }

  // AppBar 右侧按钮
  List<Widget> _buildRightButtons() {
    if (multiSelect == true) {
      return <Widget>[
        TextButton(
          child: Text(RCString.ConCancel),
          style: ButtonStyle(
            backgroundColor: MaterialStateProperty.all<Color>(Colors.white),
          ),
          onPressed: () {
            multiSelect = false;
            selectedMessageIds.clear();
            _refreshMessageContentListUI();
            _refreshUI();
          },
        )
      ];
    } else {
      return <Widget>[
        IconButton(
          icon: Image.asset('images/ic_showing_blcak.png'),
          onPressed: () {
            //跳转视频页面
            if (!CnClickUtils.isClick()) return;

            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => CnCallWaitPage(
                          nikeName: nickName ?? '',
                          avatarUrl: avatarUrl ?? '',
                        )));
          },
        ),
        IconButton(
          icon: Image.asset('images/ic_more_black.png'),
          onPressed: () {
            // _pushToDebug(); //关注拉黑弹窗
            userData?.userId = targetId;
            //更多弹窗
            CnAnchorViewModel.getInfo().showMoreDialog(context, userData,
                (value) {
              //关注、取消关注
              CnEventBus.instance!.commit(EventKeys.HomeListPageMessage, null);
              if (value == 'block') {
                Navigator.pop(context);
              } else if (value == 'follow') {
                userData?.isFollow = true;
              } else if (value == 'followed') {
                userData?.isFollow = false;
              }
            });
          },
        ),
      ];
    }
  }

  ///长按录制语音的 gif 动画
  Widget _buildExtraCenterWidget() {
    if (this.currentStatus == ConversationStatus.VoiceRecorder) {
      return CnWidgetUtil.buildVoiceRecorderWidget();
    } else {
      return CnWidgetUtil.buildEmptyWidget();
    }
  }

  // 底部输入栏
  Widget? _buildBottomInputBar() {
    if (multiSelect == true) {
      return bottomToolBar;
    } else {
      return bottomInputBar;
    }
  }

  Widget _getExtentionWidget() {
    if (currentInputStatus == InputBarStatus.Extention) {
      return Container(
          height: 200,
          child: GridView.count(
            physics: new NeverScrollableScrollPhysics(),
            crossAxisCount: 4,
            padding: EdgeInsets.all(10),
            children: extWidgetList,
          ));
    } else if (currentInputStatus == InputBarStatus.Phrases) {
      return Container(height: 200, child: _buildPhrasesList());
    } else if (currentInputStatus == InputBarStatus.Emoji) {
      return Container(height: 200, child: _buildEmojiList());
    } else {
      if (currentInputStatus == InputBarStatus.Voice) {
        bottomInputBar!.refreshUI();
      }
      return CnWidgetUtil.buildEmptyWidget();
    }
  }

  GridView _buildEmojiList() {
    return GridView(
      scrollDirection: Axis.vertical,
      gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
        maxCrossAxisExtent: MediaQuery.of(context).size.width / 8,
      ),
      children: List.generate(
        emojiList.length,
        (index) {
          return GestureDetector(
            onTap: () {
              bottomInputBar!.setTextContent(emojiList[index]);
            },
            child: Center(
              widthFactor: MediaQuery.of(context).size.width / 8,
              heightFactor: MediaQuery.of(context).size.width / 8,
              child: Text(emojiList[index], style: TextStyle(fontSize: 25)),
            ),
          );
        },
      ),
    );
  }

  ListView? _buildPhrasesList() {
    if (phrasesListView != null) {
      return phrasesListView;
    }
    return ListView.separated(
        key: UniqueKey(),
        controller: ScrollController(),
        itemCount: phrasesList.length,
        itemBuilder: (BuildContext context, int index) {
          if (phrasesList.length != null && phrasesList.length > 0) {
            String contentStr = phrasesList[index];
            return GestureDetector(
                onTap: () {
                  _clickPhrases(contentStr);
                },
                child: Container(
                  alignment: Alignment.center,
                  child: Text(contentStr,
                      style: new TextStyle(
                        fontSize: RCFont.CommonPhrasesSize,
                      )),
                  height: RCLayout.CommonPhrasesHeight,
                ));
          } else {
            return CnWidgetUtil.buildEmptyWidget();
          }
        },
        separatorBuilder: (BuildContext context, int index) {
          return Container(
            color: Color(0xffC8C8C8),
            height: 0.5,
          );
        });
  }

  void _clickPhrases(String contentStr) async {
    currentInputStatus = InputBarStatus.Normal;
    RCIMIWTextMessage? msg = await _engine!.createTextMessage(
      conversationType!,
      targetId!,
      null,
      contentStr,
    );
    if (conversationType == RCIMIWConversationType.private) {
      int duration = contentStr.length <= 20
          ? RCDuration.TextMessageBurnDuration
          : (RCDuration.TextMessageBurnDuration +
              ((contentStr.length - 20) / 2 as int));
      // msg.destructDuration = isSecretChat ? duration : 0;
    }

    _sendMessageAndNotification(msg!);
    // 统一转成了 onMessageSend 回调处理
    // _insertOrReplaceMessage(message);
  }

  @override
  void initState() {
    super.initState();
    _engine = CnGlobal.engine;

    /// 初始化动画控制器
    _controller = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: this,
    );

    _scaleController = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: this,
    );

    ///动画监听
    _controller.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _scaleController.forward();
      }
    });

    _scaleController.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _controller.reverse();
      }
    });

    //监听连接状态
    _engine?.onConnectionStatusChanged = (RCIMIWConnectionStatus? status) {
//...

      print(status);
    };
    messageContentList = MessageContentList(
        messageDataSource, multiSelect, selectedMessageIds, this, burnMsgMap);
    conversationType =
        arguments?["coversationType"] ?? RCIMIWConversationType.private;
    targetId = arguments!["targetId"];
    setState(() {
      nickName = arguments!["nickName"];
    });
    bottomInputBar = CnBottomInputBar(this);
    bottomToolBar = CnBottomToolBar(this);
    currentStatus = ConversationStatus.Normal;

    _getInfoData();
    getCoins();

    //增加加号扩展栏的 widget
    _initExtentionWidgets();
    //获取历史数据
    onGetHistoryMessages();
//监听发送消息
    sendMessageCallback = RCIMIWSendMessageCallback(
        onMessageSaved: (RCIMIWMessage? message) {},
        onMessageSent: (int? code, RCIMIWMessage? message) {
          if (message?.targetId == this.targetId) {
            // userIdList.clear();
            bottomInputBar!.clearReferenceMessage();
            _insertOrReplaceMessage(message);
          }
        });

    event = EventBusUtils.getInstance()?.on().listen((event) {
      if (event.toString() == EventKeys.applePaySuccess) {
        getCoins();
      }
    });
  }

//获取主播个人信息
  _getInfoData() {
    CnNetHelper.getUserInfo(targetId ?? '',
        (HDHResponseData configData, bool result, String msg) async {
      if (result) {
        UserInfoModel userModel = UserInfoModel.fromJson(configData.data);
        setState(() {
          nickName = userModel.nickname;
          avatarUrl = userModel.avatarUrl;
        });
      }
    });
  }

  onGetHistoryMessages() async {
    IRCIMIWGetMessagesCallback? callback =
        IRCIMIWGetMessagesCallback(onSuccess: (List<RCIMIWMessage>? t) {
//...
      if (t != null) {
        t.sort((a, b) => b.sentTime!.compareTo(a.sentTime!));
        messageDataSource = t;
      }
      // if (isFirstGetHistoryMessages) {
      //   _sendReadReceipt();
      // }
      _refreshMessageContentListUI();
      // isFirstGetHistoryMessages = false;
    }, onError: (int? code) {
//...
      print(code);
    });

    DateTime now = DateTime.now();
    int sentTime = now.millisecondsSinceEpoch;
    _engine!.getMessages(conversationType!, targetId!, null, sentTime,
        RCIMIWTimeOrder.before, RCIMIWMessageOperationPolicy.local, 20,
        callback: callback);
  }

  void _initExtentionWidgets() {
    Widget imageWidget = CnWidgetUtil.buildExtentionWidget(
        Icons.photo, RCString.ExtPhoto, () async {
      String? imgPath = await CnMediaUtil.instance!.pickImage();
      if (imgPath == null) {
        return;
      }
      if (imgPath.endsWith("gif")) {
        RCIMIWGIFMessage? gifMsg = await _engine!.createGIFMessage(
            RCIMIWConversationType.private, targetId!, null, imgPath);
        _sendMessageAndNotification(gifMsg!);
      } else {
        RCIMIWImageMessage? imgMsg = await _engine!.createImageMessage(
          RCIMIWConversationType.private,
          targetId!,
          null,
          imgPath,
        );
        _sendMessageAndNotification(imgMsg!);
      }
    });

    Widget cameraWidget = CnWidgetUtil.buildExtentionWidget(
        Icons.camera, RCString.ExtCamera, () async {
      String? imgPath = await CnMediaUtil.instance!.takePhoto();
      if (imgPath == null) {
        return;
      }
      // developer.log("imagepath " + imgPath, name: pageName);
      String temp = imgPath.replaceAll("file://", "");
      // 保存不需要 file 开头的路径
      // _saveImage(temp);
      RCIMIWImageMessage? imgMsg = await _engine!.createImageMessage(
        RCIMIWConversationType.private,
        targetId!,
        null,
        imgPath,
      );

      _sendMessageAndNotification(imgMsg!);
    });

    extWidgetList.add(imageWidget);
    extWidgetList.add(cameraWidget);
    //初始化短语
    for (int i = 0; i < 10; i++) {
      phrasesList.add('快捷回复测试用例 $i');
    }

    emojiList = Emoji.emojiList;
  }

  void _sendMessageAndNotification(RCIMIWMessage message) {
    RCIMIWAndroidPushOptions androidPushOptions =
        RCIMIWAndroidPushOptions.create();
// 此处可配置 Android 参数

    RCIMIWIOSPushOptions iosPushOptions = RCIMIWIOSPushOptions.create();
// 此处可配置 iOS 参数
    String lastMessageText = 'message';
    if (message is RCIMIWTextMessage) {
      RCIMIWTextMessage textMessage = message as RCIMIWTextMessage;
      lastMessageText = textMessage.text!;
    } else if (message is RCIMIWImageMessage) {
      lastMessageText = '[Image]';
    } else if (message is RCIMIWVoiceMessage) {
      lastMessageText = '[Voice]';
    }

    message.pushOptions = RCIMIWMessagePushOptions.create(
        disableNotification: false,
        pushContent: lastMessageText,
        pushData: '',
        androidPushOptions: androidPushOptions,
        iOSPushOptions: iosPushOptions);

    if (message is RCIMIWImageMessage || message is RCIMIWVoiceMessage) {
      //多媒体消息发送方
      RCIMIWSendMediaMessageListener? listener = RCIMIWSendMediaMessageListener(
          onMediaMessageSaved: (RCIMIWMediaMessage? message) {
//...
      }, onMediaMessageSending: (RCIMIWMediaMessage? message, int? progress) {
//...
        print(progress);
      }, onSendingMediaMessageCanceled: (RCIMIWMediaMessage? message) {
//...
      }, onMediaMessageSent: (int? code, RCIMIWMediaMessage? message) {
//...
        print(code);
        _insertOrReplaceMessage(message);
      });

      _engine!
          .sendMediaMessage(message as RCIMIWMediaMessage, listener: listener);
    } else {
      _engine!.sendMessage(message, callback: sendMessageCallback);
    }
  }

  void _insertOrReplaceMessage(RCIMIWMessage? message) {
    messageDataSource.insert(0, message);
    _refreshMessageContentListUI();
  }

  void _refreshMessageContentListUI() {
    messageContentList.updateData(
        messageDataSource, multiSelect, selectedMessageIds);
  }

  void _showExtraCenterWidget(ConversationStatus status) {
    this.currentStatus = status;
    _refreshUI();
  }

  /// 禁止随意调用 setState 接口刷新 UI，必须调用该接口刷新 UI
  void _refreshUI() {
    setState(() {});
  }

  void getCoins() {
    CnNetHelper.getUserCoins().then((value) {
      setState(() {
        availableCoins = value;
      });
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    CnEventBus.instance!.commit(EventKeys.ConversationPageDispose, null);
    CnEventBus.instance!.commit(EventKeys.HomeListPageMessage, null);
    EventBusUtils.getInstance()?.fire(EventKeys.applePaySuccess);
    event?.cancel();
    _scaleController.dispose();
    _controller.dispose();
    _giftTimer?.cancel();
  }

  @override
  void didTapDelete() {
    // TODO: implement didTapDelete
  }

  @override
  void didTapExtentionButton() {
    // TODO: implement didTapExtentionButton
  }

  @override
  void didTapForward() {
    // TODO: implement didTapForward
  }

  @override
  void inputStatusDidChange(InputBarStatus status) {
    // TODO: implement inputStatusDidChange
    setState(() {
      currentInputStatus = status;
    });
    bottomInputBar!.refreshUI();
    _refreshUI();
  }

  @override
  void onTextChange(String text) {
    // TODO: implement onTextChange
    //  textDraft = text;

    _engine?.sendTypingStatus(
        conversationType!, targetId!, null, 'Inputting...');
  }

  @override
  void willSendText(String text) async {
    // TODO: implement willSendText
    RCIMIWMessage msg;
    if (bottomInputBar!.getReferenceMessage() != null) {
      RCIMIWReferenceMessage referenceMessage =
          bottomInputBar!.getReferenceMessage()!;
      referenceMessage.text = text;
      msg = referenceMessage;
    } else {
      RCIMIWTextMessage? textMessage = await _engine!.createTextMessage(
        conversationType!,
        targetId!,
        null,
        text,
      );
      msg = textMessage!;
    }
    if (conversationType == RCIMIWConversationType.private) {
      int duration = RCDuration.TextMessageBurnDuration;
      if (text.length > 20) {
        int textLength = text.length - 20;
        int tempDuration = (textLength / 2).ceil();
        duration += tempDuration;
      }
    }

    _sendMessageAndNotification(msg!);
  }

  @override
  void willSendVoice(String? path, int? duration) async {
    // TODO: implement willSendVoice
    RCIMIWVoiceMessage? voiceMessage = await _engine!.createVoiceMessage(
      conversationType!,
      targetId!,
      null,
      path!,
      duration!,
    );
    if (conversationType == RCIMIWConversationType.private) {}

    _sendMessageAndNotification(voiceMessage!);
  }

  @override
  void willStartRecordVoice() {
    _showExtraCenterWidget(ConversationStatus.VoiceRecorder);
    _engine?.sendTypingStatus(conversationType!, targetId!, null, 'Voicing...');
  }

  @override
  void willStopRecordVoice() {
    _showExtraCenterWidget(ConversationStatus.Normal);
  }

  @override
  void didLongPressMessageItem(RCIMIWMessage? message, Offset? tapPos) {
    // TODO: implement didLongPressMessageItem
  }

  @override
  void didLongPressUserPortrait(String? userId, Offset? tapPos) {
    // TODO: implement didLongPressUserPortrait
  }

  @override
  void didSendMessageRequest(RCIMIWMessage? message) {
    // TODO: implement didSendMessageRequest
  }

  @override
  void didTapItem(RCIMIWMessage? message) {
    // TODO: implement didTapItem
  }

  @override
  void didTapMessageItem(RCIMIWMessage? message) {
    // TODO: implement didTapMessageItem
  }

  @override
  void didTapMessageReadInfo(RCIMIWMessage? message) {
    // TODO: implement didTapMessageReadInfo
  }

  @override
  void didTapReSendMessage(RCIMIWMessage? message) {
    // TODO: implement didTapReSendMessage
  }

  @override
  void didTapUserPortrait(String userId) {
    // TODO: implement didTapUserPortrait
  }

  @override
  void willpullMoreHistoryMessage() {
    // TODO: implement willpullMoreHistoryMessage
  }


//规则弹窗
void _showGiftDialog(context, FunctionTest<int> backBlock) {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        // backgroundColor: Color(0xFFDACED8),
        // shape: RoundedRectangleBorder(
        //   // borderRadius: BorderRadius.circular(10.0), // 设置边框半径
        //   side: BorderSide(color: Color(0xCC50082F), width: 3.0), // 设置边框颜色和宽度
        // ),
        contentPadding: const EdgeInsets.all(0),
        content: Container(
          decoration: const BoxDecoration(
              image: DecorationImage(
                  fit: BoxFit.fill,
                  image: AssetImage('images/icon_gift_bg.png'))),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                // width: double.infinity,
                height: 44,
                child: Container(
                  margin: EdgeInsets.only(left: 16),
                  width: 76,
                  height: 30,
                  decoration: BoxDecoration(
                      image: DecorationImage(
                    image: AssetImage('images/icon_mate_btn_bg_coin.png'),
                  )),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Container(
                        width: 19,
                        height: 17,
                        margin: EdgeInsets.only(left: 0),
                        child: Image.asset('images/icon_coins_logo_mine.png'),
                      ),
                      Container(
                        margin: EdgeInsets.only(left: 5),
                        child: Text(
                          '$availableCoins',
                          style:
                              TextStyle(fontSize: 13, color: Color(0xFF404040)),
                        ),
                      )
                    ],
                  ),
                ),
              ),
              SizedBox(
                height: 40,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  InkWell(
                    onTap: () {
                      backBlock(1);
                      Navigator.of(context).pop();
                    },
                    child: Column(
                      children: [
                        Container(
                          width: 48,
                          height: 39,
                          child: Image.asset('images/icon_gift_pc1.png'),
                        ),
                        const SizedBox(height: 6),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Container(
                              width: 19,
                              height: 17,
                              margin: EdgeInsets.only(left: 0),
                              child: Image.asset(
                                  'images/icon_coins_logo_mine.png'),
                            ),
                            Container(
                              margin: EdgeInsets.only(left: 5),
                              child: Text(
                                '39',
                                style: TextStyle(
                                    fontSize: 13, color: Color(0xFF404040)),
                              ),
                            )
                          ],
                        ),
                      ],
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      backBlock(2);
                      Navigator.of(context).pop();
                    },
                    child: Column(
                      children: [
                        Container(
                          width: 48,
                          height: 39,
                          child: Image.asset('images/icon_gift_pc2.png'),
                        ),
                        const SizedBox(height: 6),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Container(
                              width: 19,
                              height: 17,
                              margin: EdgeInsets.only(left: 0),
                              child: Image.asset(
                                  'images/icon_coins_logo_mine.png'),
                            ),
                            Container(
                              margin: EdgeInsets.only(left: 5),
                              child: Text(
                                '39',
                                style: TextStyle(
                                    fontSize: 13, color: Color(0xFF404040)),
                              ),
                            )
                          ],
                        ),
                      ],
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      backBlock(3);
                      Navigator.of(context).pop();
                    },
                    child: Column(
                      children: [
                        Container(
                          width: 48,
                          height: 39,
                          child: Image.asset('images/icon_gift_pc3.png'),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Container(
                              width: 19,
                              height: 17,
                              margin: EdgeInsets.only(left: 0),
                              child: Image.asset(
                                  'images/icon_coins_logo_mine.png'),
                            ),
                            Container(
                              margin: EdgeInsets.only(left: 5),
                              child: Text(
                                '39',
                                style: TextStyle(
                                    fontSize: 13, color: Color(0xFF404040)),
                              ),
                            )
                          ],
                        ),
                      ],
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      backBlock(4);
                      Navigator.of(context).pop();
                    },
                    child: Column(
                      children: [
                        Container(
                          width: 48,
                          height: 39,
                          child: Image.asset('images/icon_gift_pc4.png'),
                        ),
                        const SizedBox(height: 6),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Container(
                              width: 19,
                              height: 17,
                              margin: EdgeInsets.only(left: 0),
                              child: Image.asset(
                                  'images/icon_coins_logo_mine.png'),
                            ),
                            Container(
                              margin: EdgeInsets.only(left: 5),
                              child: Text(
                                '39',
                                style: TextStyle(
                                    fontSize: 13, color: Color(0xFF404040)),
                              ),
                            )
                          ],
                        ),
                      ],
                    ),
                  )
                ],
              ),
              const SizedBox(height: 52),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  InkWell(
                    onTap: () {
                      backBlock(0);
                      Navigator.of(context).pop();
                    },
                    child: Container(
                        margin: EdgeInsets.only(right: 16),
                        // width: 252,
                        height: 40,
                        alignment: Alignment.center,
                        decoration: const BoxDecoration(
                            image: DecorationImage(
                                image: AssetImage(
                                    'images/icon_coin_bg_mine.png'))),
                        child: Container(
                          padding: EdgeInsets.all(10),
                          child: Text(
                            'Coin Store',
                            style: TextStyle(
                                fontSize: 18, color: Color(0xFFE71988)),
                          ),
                        )),
                  ),
                ],
              ),
              const SizedBox(height: 12),
            ],
          ),
        ),
      );
    },
  );
}
}


